/**
 * 新API流程测试
 * 
 * 该文件用于测试新的API流程，验证数据上传和结果获取的完整性
 * 新流程特点：
 * - 数据上传时直接返回分析结果，无需轮询
 * - 使用TabletBrainWaveResponse格式
 * - 睡眠阶段值为：wake, n1, n2, n3, rem
 * 
 * 测试原理：
 * - 模拟发送脑波数据到服务端
 * - 验证响应格式是否正确
 * - 检查分析结果是否包含预期字段
 */

package com.example.brain_wave.test.api_flow

import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.example.brain_wave.api.AnalysisApiClient
import com.example.brain_wave.api.model.TabletBrainWaveResponse
import com.example.brain_wave.data.AnalysisDataManager
import com.example.brain_wave.data.AnalysisDataManagerState
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.delay
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*

@RunWith(AndroidJUnit4::class)
class NewApiFlowTest {
    
    private lateinit var context: Context
    private lateinit var analysisDataManager: AnalysisDataManager
    private var receivedResponse: TabletBrainWaveResponse? = null
    private var currentState: AnalysisDataManagerState = AnalysisDataManagerState.IDLE
    
    @Before
    fun setup() {
        context = ApplicationProvider.getApplicationContext()
        analysisDataManager = AnalysisDataManager(context)
        
        // 初始化分析数据管理器
        analysisDataManager.initialize(
            baseUrl = "http://192.168.2.12:8000",
            roomId = "test_room_001",
            userId = "test_user_001"
        )
        
        // 设置回调
        analysisDataManager.setOnStateChanged { state ->
            currentState = state
            println("📊 状态变化: $state")
        }
        
        analysisDataManager.setOnAnalysisResult { result ->
            receivedResponse = result
            println("📊 收到分析结果: success=${result.success}, sleep_stage=${result.sleep_stage}")
        }
        
        analysisDataManager.setOnError { error ->
            println("❌ 错误: $error")
        }
    }
    
    @Test
    fun testNewApiFlow() = runBlocking {
        println("🚀 开始测试新API流程")
        
        // 1. 验证初始状态
        assertEquals("初始状态应为IDLE", AnalysisDataManagerState.IDLE, currentState)
        
        // 2. 开始数据流程
        analysisDataManager.startDataFlow()
        
        // 3. 等待状态变化和数据处理
        var waitTime = 0
        while (receivedResponse == null && waitTime < 30000) { // 最多等待30秒
            delay(1000)
            waitTime += 1000
            println("⏳ 等待响应... ${waitTime/1000}秒")
        }
        
        // 4. 验证响应
        assertNotNull("应该收到分析响应", receivedResponse)
        
        receivedResponse?.let { response ->
            // 验证基本字段
            assertTrue("响应应该包含session_id", response.session_id.isNotEmpty())
            assertTrue("响应应该包含timestamp", response.timestamp > 0)
            assertTrue("响应应该包含received_data_points", response.received_data_points >= 0)
            assertTrue("响应应该包含buffer_size", response.buffer_size >= 0)
            assertTrue("响应应该包含analysis_duration_ms", response.analysis_duration_ms >= 0)
            
            // 验证分析结果字段（如果成功）
            if (response.success) {
                println("✅ 分析成功，验证结果字段")
                
                // 验证睡眠阶段
                response.sleep_stage?.let { stage ->
                    assertTrue("睡眠阶段应为有效值", 
                        stage in listOf("wake", "n1", "n2", "n3", "rem"))
                    println("✅ 睡眠阶段: $stage")
                }
                
                // 验证置信度
                response.confidence?.let { confidence ->
                    assertTrue("置信度应在0.0-1.0范围内", confidence in 0.0..1.0)
                    println("✅ 置信度: $confidence")
                }
                
                // 验证频域功率比例
                response.frequency_bands?.let { bands ->
                    assertTrue("Delta频段应在0.0-1.0范围内", bands.delta in 0.0..1.0)
                    assertTrue("Theta频段应在0.0-1.0范围内", bands.theta in 0.0..1.0)
                    assertTrue("Alpha频段应在0.0-1.0范围内", bands.alpha in 0.0..1.0)
                    assertTrue("Beta频段应在0.0-1.0范围内", bands.beta in 0.0..1.0)
                    assertTrue("Gamma频段应在0.0-1.0范围内", bands.gamma in 0.0..1.0)
                    println("✅ 频域功率比例验证通过")
                }
                
                // 验证YASA分析器状态
                response.yasa_available?.let { available ->
                    println("✅ YASA分析器可用性: $available")
                }
            } else {
                println("⚠️ 分析未成功，消息: ${response.message}")
            }
        }
        
        // 5. 停止数据流程
        analysisDataManager.stopDataFlow()
        
        // 6. 验证最终状态
        delay(1000) // 等待状态更新
        assertEquals("最终状态应为IDLE", AnalysisDataManagerState.IDLE, currentState)
        
        println("✅ 新API流程测试完成")
    }
    
    @Test
    fun testResponseFormat() {
        println("🔍 测试响应格式")
        
        // 创建模拟响应
        val mockResponse = TabletBrainWaveResponse(
            success = true,
            message = "Analysis completed successfully",
            session_id = "test_session_123",
            timestamp = System.currentTimeMillis(),
            received_data_points = 512,
            buffer_size = 1024,
            analysis_duration_ms = 150,
            sleep_stage = "n2",
            confidence = 0.85,
            frequency_bands = com.example.brain_wave.api.model.FrequencyBandRatios(
                delta = 0.25,
                theta = 0.20,
                alpha = 0.15,
                beta = 0.30,
                gamma = 0.10
            ),
            yasa_available = true
        )
        
        // 验证响应格式
        assertTrue("success字段应为true", mockResponse.success)
        assertEquals("session_id应匹配", "test_session_123", mockResponse.session_id)
        assertEquals("sleep_stage应为n2", "n2", mockResponse.sleep_stage)
        assertEquals("confidence应为0.85", 0.85, mockResponse.confidence!!, 0.001)
        
        // 验证频域功率比例总和接近1.0
        mockResponse.frequency_bands?.let { bands ->
            val total = bands.delta + bands.theta + bands.alpha + bands.beta + bands.gamma
            assertEquals("频域功率比例总和应接近1.0", 1.0, total, 0.01)
        }
        
        println("✅ 响应格式验证通过")
    }
    
    @Test
    fun testSleepStageMapping() {
        println("🛏️ 测试睡眠阶段映射")
        
        val sleepStages = listOf("wake", "n1", "n2", "n3", "rem")
        
        sleepStages.forEach { stage ->
            val mockResponse = TabletBrainWaveResponse(
                success = true,
                message = "Test",
                session_id = "test",
                timestamp = System.currentTimeMillis(),
                received_data_points = 1,
                buffer_size = 1,
                analysis_duration_ms = 1,
                sleep_stage = stage
            )
            
            assertNotNull("睡眠阶段 $stage 应该有效", mockResponse.sleep_stage)
            assertEquals("睡眠阶段应匹配", stage, mockResponse.sleep_stage)
        }
        
        println("✅ 睡眠阶段映射验证通过")
    }
}